package www.wen.com.common.util;

import android.os.Parcelable
import com.tencent.mmkv.MMKV
import java.util.Collections

/**
 * @author WEN
 * @Description: MMKV数据存储工具类
 * @date 2021/1/28 21:32
 */
object SpUtil {

    private var mmkv: MMKV = MMKV.defaultMMKV()

    fun encode(key: String, value: Any?) {
        when (value) {
            is String -> mmkv.encode(key, value)
            is Float -> mmkv.encode(key, value)
            is Boolean -> mmkv.encode(key, value)
            is Int -> mmkv.encode(key, value)
            is Long -> mmkv.encode(key, value)
            is Double -> mmkv.encode(key, value)
            is ByteArray -> mmkv.encode(key, value)
            else -> return
        }
    }

    fun <T : Parcelable> encode(key: String, t: T?) {
        if(t ==null){
            return
        }
        mmkv.encode(key, t)
    }

    fun encode(key: String, sets: Set<String>?) {
        if(sets ==null){
            return
        }
        mmkv.encode(key, sets)
    }

    fun decodeInt(key: String,defaultValue:Int = -1): Int {
        return mmkv.decodeInt(key, defaultValue)
    }

    fun decodeDouble(key: String,defaultValue:Double = -1.0): Double {
        return mmkv.decodeDouble(key, defaultValue)
    }

    fun decodeLong(key: String,value: Long = -1L): Long {
        return mmkv.decodeLong(key, value)
    }

    fun decodeBoolean(key: String,defaultValue:Boolean = false): Boolean {
        return mmkv.decodeBool(key, defaultValue)
    }

    fun decodeFloat(key: String): Float {
        return mmkv.decodeFloat(key, 0F)
    }

    fun decodeByteArray(key: String): ByteArray? {
        return mmkv.decodeBytes(key)
    }

    fun decodeString(key: String,defaultValue:String = ""): String? {
        return mmkv.decodeString(key, defaultValue)
    }

    fun <T : Parcelable> decodeParcelable(key: String, tClass: Class<T>): T? {
        return mmkv.decodeParcelable(key, tClass)
    }

    fun decodeStringSet(key: String): Set<String>? {
        return mmkv.decodeStringSet(key, Collections.emptySet())
    }

    fun removeKey(key: String) {
        mmkv.removeValueForKey(key)
    }

    fun clearAll() {
        mmkv.clearAll()
    }

    fun clearAllExcludeKey(vararg args:String) {
        mmkv.allKeys()?.filter { key1->
            var isIn = true
            run{
                args.forEach { key2->
                    if(key1 == key2){
                        isIn = false
                        return@run
                    }
                }
            }
            isIn
        }.run {
            this?.forEach {
                removeKey(it)
            }
        }
    }

}